//
//  ViewController.swift
//  UIStackViewDemo
//
//  Created by 李煜 on 2024/9/18.
//

import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    m1()
    m2()
  }

  func m1() {
    let stackView = UIStackView()
    stackView.backgroundColor = .gray
    view.addSubview(stackView)
    stackView.axis = .horizontal // 或 .vertical
    stackView.alignment = .fill   // 控制子视图的对齐方式
    stackView.distribution = .fillEqually // 控制子视图的大小分配
    stackView.spacing = 10 // 子视图之间的间距
    
    let label = UILabel()
    label.backgroundColor = .red
    let button = UIButton()
    button.backgroundColor = .blue
    stackView.addArrangedSubview(label)
    stackView.addArrangedSubview(button)

    stackView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
      stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100)
    ])

  }
  func m2() {
    let button1 = UIButton(type: .system)
    button1.setTitle("Button 1", for: .normal)
    button1.backgroundColor = .green

    let button2 = UIButton(type: .system)
    button2.setTitle("Button 2", for: .normal)
    button2.backgroundColor = .orange

    let stackView = UIStackView(arrangedSubviews: [button1, button2])
    stackView.backgroundColor = .brown
    stackView.axis = .horizontal
    stackView.spacing = 8
    stackView.alignment = .center
    stackView.distribution = .fillEqually
    
    view.addSubview(stackView)
    
    // 设置 Auto Layout
    stackView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
      stackView.heightAnchor.constraint(equalToConstant: 50),
      stackView.widthAnchor.constraint(equalToConstant: 200)
    ])

  }
}

